using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using System;

namespace IQIGame.Onigao.Game
{
    internal abstract class Counter : IReusableClass
    {
        public uint id { get; private set; }
        /// <summary>
        /// 帧刷间隔
        /// </summary>
        public float Interval { get; private set; }

        /// <summary>
        /// 帧刷处理函数
        /// </summary>
        public Action Handler { get; private set; }

        /// <summary>
        /// 循环次数（-1代表无限循环）
        /// </summary>
        public int Loop { get; protected set; }

        /// <summary>
        /// 计数器
        /// </summary>
        protected float _Counter = 0f;

        /// <summary>
        /// 是否已失效
        /// </summary>
        public bool Expired { get; protected set; }

        /// <summary>
        /// 支持Unitask
        /// </summary>
        public AutoResetUniTaskCompletionSource autoResetUniTask { get; set; }

        public Counter()
        {

        }

        public void Init(uint id, float interval, Action handler, int loop)
        {
            this.id = id;
            this.Interval = interval;
            this.Handler = handler;
            this.Loop = loop;
        }

        public UniTask AwaitCount()
        {
            if (autoResetUniTask != null)
            {
                return autoResetUniTask.Task;
            }
            autoResetUniTask = AutoResetUniTaskCompletionSource.Create();
            return autoResetUniTask.Task;
        }

        private void InvokeTaskResult()
        {
            if (autoResetUniTask == null)
            {
                return;
            }
            // 注意！这里要先置空，再调用，TrySetResult会先调用await之后的代码，如果await之后有给TaskSource赋新值，然后这里再置空，那么_completeActTaskSource就永远为null了。
            // 若置空不及时导致了多次source.TrySetResult，会导致池内数据异常
            var autoTask = autoResetUniTask;
            autoResetUniTask = null;
            autoTask.TrySetResult();
        }

        private void InvokeTaskCancel()
        {
            if (autoResetUniTask == null)
            {
                return;
            }
            var autoTask = autoResetUniTask;
            autoResetUniTask = null;
            autoTask.TrySetCanceled();
        }

        public virtual void OnUpdate(float deltaTime, float unscaledDeltaTime)
        {
            if (Expired)
            {
                return;
            }

            AddCount(deltaTime, unscaledDeltaTime);

            if (_Counter >= Interval)
            {
                if (Loop < 0)
                {
                    _Counter -= Interval;
                    CallComplete();
                    return;
                }
                Loop--;
                if (Loop <= 0)
                {
                    Expired = true;
                    CallComplete();
                }
                else
                {
                    _Counter -= Interval;
                    CallComplete();
                }
            }
        }

        public void Stop(bool invokeComplete)
        {
            if (Expired)
            {
                return;
            }
            Expired = true;
            if (invokeComplete)
            {
                CallComplete();
            }
            else
            {
                InvokeTaskCancel();
            }
        }

        protected virtual void CallComplete()
        {
            try
            {
                Handler?.Invoke();
                InvokeTaskResult();
            }
            catch (Exception e)
            {
                LogGame.LogError(e);
            }
        }

        protected abstract void AddCount(float deltaTime, float unscaledDeltaTime);

        public uint MaxStore => 50;

        public void OnReset()
        {
            id = 0;
            Interval = 0;
            Loop = 0;
            Handler = null;
            Expired = false;
            _Counter = 0;
            InvokeTaskCancel();
        }
    }
}
